import java.util.Arrays;

public class Solution905 {
    public int[] sortArrayByParity(int[] nums) {
        int l=0,r=nums.length-1;
        while (l<r){
            while (l<nums.length && nums[l]%2==0){
                l++;
            }
            while (r>=0 && nums[r]%2==1){
                r--;
            }
            if (l==nums.length || r<0){
                break;
            }
            if (l<=r){
                int t=nums[l];
                nums[l]=nums[r];
                nums[r]=t;
                l++;
                r--;
            }
        }
        return nums;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution905().sortArrayByParity(new int[]{3, 1, 2, 4})));
    }
}
